<template>
  <div class="mainDiv" v-loading="pageLoading">
    <div class="topDiv">
      <!-- <div class="justBackColor"></div>
      <p>客户需求</p>-->
      <el-button size="small" style="width:80px;margin-left:10px" @click="btnBack">返回</el-button>
      <div style="float:right; margin-right:50px">
        <el-button size="small" type="primary" style="width:80px;" @click="btnAdd">确定</el-button>
      </div>
    </div>
    <div class="justDiv">
      <el-form :model="demand" ref="demand" :rules="demandRules" label-width="120px">
        <!-- <el-form-item label="项目名称" prop="name">
            <el-input v-model="ruleForm2.name"></el-input>
        </el-form-item>-->
        <div class="justDivCon flex-between">
          <div class="flex1">
            <el-form-item label="客户名称：" label-width="120px" prop="customValue">
              <el-select
                placeholder="请选择"
                v-model="demand.customValue"
                filterable
                @change="selectCust"
              >
                <el-option
                  v-for="item in customer"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>

          <div class="flex1">
            <el-form-item label="产品编码：" label-width="120px" prop="productCodeValue">
              <el-select
                filterable
                placeholder="请选择"
                v-model="demand.productCodeValue"
                remote
                :remote-method="remoteFixtureMethod"
                :loading="loading"
                @change="selectCode"
                v-show="show"
              >
                <el-option
                  v-for="(item,index) in productCode"
                  :key="index"
                  :label="item.code"
                  :value="item"
                ></el-option>
              </el-select>

              <el-input
                v-model="demand.productCodeValue"
                style="width:215px"
                placeholder="请输入产品编码"
                v-show="isShows"
              ></el-input>
              <el-button
                type="primary"
                size="small"
                icon="el-icon-plus"
                style="margin-left:10px"
                @click="btnShow"
              >{{newCode}}</el-button>
            </el-form-item>
          </div>
        </div>
        <div class="justDivCon flex-between">
          <div class="flex1">
            <el-form-item label="产品名称：" label-width="120px" prop="productName">
              <el-input v-model="demand.productName" style="width:215px" placeholder="请输入内容"></el-input>
            </el-form-item>
          </div>

          <div class="flex1">
            <el-form-item label="产品规格：" label-width="120px" prop="proSpecification">
              <el-input v-model="demand.proSpecification" style="width:215px"></el-input>
            </el-form-item>
          </div>
        </div>

        <div class="justDivCon flex-between">
          <div class="flex1">
            <el-form-item label="报价工厂：" label-width="120px" prop="factoryValue">
              <el-select placeholder="请选择" v-model="demand.factoryValue" @change="selectFatory">
                <el-option
                  v-for="item in productFatory"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>

          <div class="flex1">
            <el-form-item label="产品类型：" label-width="120px" prop="typeValue">
              <el-select placeholder="请选择" v-model="demand.typeValue" @change="selectType">
                <el-option
                  v-for="item in productType"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>
        </div>

        <div class="justDivCon flex-between">
          <div class="flex1">
            <el-form-item label="我司合作主体：" label-width="120px" prop="companyValue">
              <el-select
                filterable
                v-model="demand.companyValue"
                placeholder="请选择"
                @change="seleCompany"
              >
                <el-option
                  v-for="item in isCompany"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>
          <div class="flex1">
            <el-form-item label="是否含税：" label-width="120px" prop="isRevenueValue">
              <el-select v-model="demand.isRevenueValue" placeholder="请选择" @change="seleRevenue">
                <el-option
                  v-for="item in isRevenue"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>
        </div>

        <div class="justDivCon flex-between">
          <div class="flex1">
            <el-form-item label="加工工艺：" label-width="120px" prop="processingVaule">
              <el-checkbox-group
                v-model="demand.processingVaule"
                @change="handleCheckedCitiesChange"
                style="display: inline-block;"
              >
                <el-checkbox
                  v-for="ChangeValue in processing"
                  :label="ChangeValue"
                  :key="ChangeValue"
                >{{ChangeValue}}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </div>

          <div class="flex1">
            <el-form-item label="合作模式：" label-width="120px" prop="cooperationValue">
              <el-radio-group v-model="demand.cooperationValue" @change="onChange1">
                <el-radio
                  :label="item.value"
                  v-for="(item,index) in cooperation"
                  :key="index"
                >{{item.name}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
        </div>

        <!-- <div class="justDivCon flex-between">
        <div class="flex1">
          <em>*</em>客供治具：
          <el-select v-model="fixtures" placeholder="请选择" @change="seleFixtures">
            <el-option
              v-for="item in forFixtures"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            ></el-option>
          </el-select>
        </div>
        </div>-->
        <div class="justDivCon flex-between">
          <div class="flex1">
            <el-form-item label="损耗率：" label-width="120px">
              <div class="flex">
                <span class="flex" style="width: 80px">
                  A
                  <checkInput style="margin: 0 10px" :inValue.sync="demand.coefficientA"
                  :prop="{
                    type: 'number',
                    size: 'medium',
                    precision: 0,
                    fill: true,
                    unit: '',
                    placeholder: '',
                    integer: false,
                    range: [0, 1000]
                  }"
                  ></checkInput>
                  ‰
                </span>
                <span class="flex" style="width: 80px; margin-left:80px">
                  B
                  <checkInput style="margin: 0 10px" :inValue.sync="demand.coefficientB"
                  :prop="{
                    type: 'number',
                    size: 'medium',
                    precision: 0,
                    fill: true,
                    unit: '',
                    placeholder: '',
                    integer: false,
                    range: [0, 1000]
                  }"
                  ></checkInput>
                  ‰
                </span>
                <span class="flex" style="width: 80px; margin-left:80px">
                  C
                  <checkInput style="margin: 0 10px" :inValue.sync="demand.coefficientC"
                  :prop="{
                    type: 'number',
                    size: 'medium',
                    precision: 0,
                    fill: true,
                    unit: '',
                    placeholder: '',
                    integer: false,
                    range: [0, 1000]
                  }"
                  ></checkInput>
                  ‰
                </span>
              </div>
            </el-form-item>
          </div>
          <div class="flex1">
            <el-form-item label="出货要求：" label-width="120px" prop="requirementValue">
              <el-radio-group v-model="demand.requirementValue" @change="onChange2">
                <el-radio
                  :label="item.value"
                  v-for="(item,index) in isRequirements"
                  :key="index"
                >{{item.name}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
        </div>

        <div class="justDivCon flex-between">
          <div class="flex1">
            <el-form-item label="账期：" label-width="120px" prop="paymentDay"
            :rules="[
              { validator: checkPaymentDay, trigger: 'blur'}
            ]">
              <el-input v-model.number="demand.paymentDay" placeholder="请输入数字0-1000" style="width:210px;margin:0 10px 0 5px"></el-input>天
            </el-form-item>
          </div>

          <div class="flex1">
            <el-form-item label="物流费收费方式:" label-width="120px" prop="logisticsChargeType ">
              <el-radio-group v-model="demand.logisticsChargeType" @change="onChange4">
                <el-radio
                  :label="item.value"
                  v-for="(item,index) in logistics"
                  :key="index"
                >{{item.name}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
        </div>

        <div class="justDivCon flex-between">
          <div class="flex1">
            <el-form-item label="库存物料是否回购：" label-width="140px" prop="buyBackValue">
              <el-radio-group v-model="demand.buyBackValue" @change="onChange3">
                <el-radio
                  :label="item.value"
                  v-for="(item,index) in isBuyBack"
                  :key="index"
                >{{item.name}}</el-radio>
              </el-radio-group>
              <span style="margin-left:50px" v-show="hgShow">
                库存回购天数
                <el-input v-model="demand.buyBackData" style="width:80px;margin:0 10px 0 5px"></el-input>天
              </span>
            </el-form-item>
          </div>

          <div class="flex1" v-show="isShow">
            <el-form-item label="垫资费率:" label-width="120px" prop="advanceProp"  :rules="[
              { validator: checkAdvanceProp, trigger: 'blur'}
            ]">
              <el-input v-model.number="demand.advanceProp" placeholder="请输入数字0-100" style="width:210px;margin:0 10px 0 5px"></el-input>%/天
            </el-form-item>
          </div>
        </div>

        <div class="justDivCon flex-between">
          <div class="flex2">
            <el-form-item label="客户文件:" label-width="120px" prop="upFile">
              <el-tag v-if="demand.upFile.name">{{demand.upFile.name}}</el-tag>
              <FileUpload @FileList="uploadFile" style="margin-left:20px"></FileUpload>
            </el-form-item>
          </div>
        </div>

        <div class="justDivCon flex-between">
          <div class="flex2">
            <span style="inline-block;height:100px">备注说明：</span>
            <el-input
              type="textarea"
              v-model="demand.textarea"
              :rows="5"
              style="width:70%;margin:0 10px 0 5px"
            ></el-input>
          </div>
        </div>
      </el-form>
      <!-- <div class="btnBtom">
        <el-button>取消</el-button>
        <el-button type="primary" @click="btnAdd">确定</el-button>
      </div>-->
    </div>
  </div>
</template>

<script>
import FileUpload from '@/components/FileUploadAemand'
import checkInput from '@/components/checkInput'
export default {
  components: {
    FileUpload,
    checkInput
  },
  data() {
    return {
      pageLoading: false,
      demand: {
        cooperationValue: 'JG', //合作模式
        customValue: '', //客户名称值
        factoryValue: '', //报价工厂选择值
        typeValue: '', //类型值
        productCodeValue: '', //产品编码值
        productName: '', //产品名称
        proSpecification: '', //产品规格
        processingVaule: [], //加工工艺
        fixtures: '1', //客供治具
        upFile: [],
        coefficientA: '', //耗损率
        coefficientB: '', //耗损率
        coefficientC: '', //耗损率
        isRevenueValue: '1', //是否含税
        companyValue: '', //我司合作主体
        requirementValue: '', //出货要求
        buyBackValue: '0', //是否回购
        buyBackData: '', //回购天数
        period: '', //对账周期
        paymentDay: '', //账期
        textarea: '', //备注说明
        advanceProp: '', //垫资比例
        logisticsChargeType: '', //物流费
      },
      loading: false,
      demandRules: {
        customValue: [
          { required: true, trigger: 'blur', message: '请选择客户名称' },
        ],
        productCodeValue: [
          { required: true, trigger: 'blur', message: '请选择产品编码' },
        ],
        proSpecification: [
          { required: true, trigger: 'blur', message: '请输入产品规格' },
        ],
        productName: [
          { required: true, trigger: 'blur', message: '请输入品名称' },
        ],
        factoryValue: [
          { required: true, trigger: 'blur', message: '请选择报价工厂' },
        ],
        typeValue: [
          { required: true, trigger: 'blur', message: '请选择产品类型' },
        ],
        companyValue: [
          { required: true, trigger: 'blur', message: '请选择我司合作主体' },
        ],
        isRevenueValue: [
          { required: true, trigger: 'blur', message: '请选择是否含税' },
        ],
        processingVaule: [
          { required: true, trigger: 'blur', message: '请选择加工工艺' },
        ],
        upFile: [{ required: true, trigger: 'blur', message: '请上传文件' }],
      },
      newCode: '添加新编码',
      isShow: false,
      isShows: false,
      hgShow: false,
      show: true,
      customer: [], //客户名称
      productCode: [], //产品编码
      processing: ['SMT', 'DIP', 'TEST', 'PACK'], //加工工艺
      processingMap: {SMT: "CI1", DIP: "CI2", TEST: "CI3", PACK: "CI4"},
      productFatory: [{ name: '富润通', value: '1' }], //报价工厂
      logistics: [
        {
          name: '无',
          value: '0',
        },
        {
          name: '实报实销',
          value: '1',
        },
        {
          name: '按片收',
          value: '2',
        },
      ],
      productType: [
        { name: '主板', value: '主板' },
        { name: '内存条', value: '内存条' },
        { name: 'SSD', value: 'SSD' },
        { name: '机顶盒', value: '机顶盒' },
        { name: '显卡', value: '显卡' },
        { name: '服务器', value: '服务器' },
        { name: '其他', value: '其他' },
      ], //产品类型
      forFixtures: [
        { name: '有', value: '1' },
        { name: '无', value: '0' },
      ], //客供治具
      cooperation: [
        // { name: '加工', value: 'JG' },
        // { name: '代采', value: 'DC_JG' },
        // { name: '代采+加工', value: 'DZ_JG' },
        // { name: '垫资+加工', value: 'DC' },
      ], //合作模式
      isRevenue: [
        { name: '含税', value: '1' },
        { name: '不含税', value: '0' },
      ], //我司合作主体
      isCompany: [
        // {
        //   name: '品鑫泰供应链（深圳）有限公司',
        //   value: '1',
        // },
        // {
        //   name: '龙华工厂',
        //   value: '100052',
        // },
        // {
        //   name: '盐田工厂',
        //   value: '1',
        // },
        // {
        //   name: '品新香港',
        //   value: '100052',
        // },
      ], //是否含税
      isRequirements: [
        { name: '散货出', value: '1' },
        { name: '栈板出', value: '2' },
        { name: '静电箱出', value: '3' },
        { name: '周转箱出', value: '4' },
      ], //出货要求
      isBuyBack: [
        { name: '回购', value: '1' },
        { name: '不回购', value: '0' },
      ], //是否回购
    }
  },
  created() {
    this.getCustomer()
    this.getComboCoop()
    this.getOrganization()
    // this.getFixt1()
  },
  methods: {
    /* 检查垫资率 */
    checkAdvanceProp (rule, value, callback) {
      if (value == '') {
        callback()
      } else if (!Number.isInteger(value)) {
        callback(new Error('请输入数字值'))
      } else {
        if (value < 0 || value > 101) {
          callback(new Error('请输入正确天数'))
        } else {
          callback()
        }
      }
    },
    /* 检查账期 */
    checkPaymentDay (rule, value, callback) {
      if (value == '') {
        callback()
      } else if (!Number.isInteger(value)) {
        callback(new Error('请输入数字值'));
      } else {
        callback()
      }
    },
    /* 产品编码模糊查询 */
    remoteFixtureMethod (query) {
      if (query !== '') {
        this.loading = true
        setTimeout(async () => {
          await this.getMaterial1(query, this.$route.query.id)
          this.loading = false
        }, 200)
      } else {
      }
    },
    //查询客户名称
    getCustomer() {
      this.$quote
        .getComboCustomer()
        .then((res) => {
          console.log(res)
          if (res.code == 200) {
            this.customer = res.data
          } else {
            this.$message.error(res.code + '-' + res.msg)
          }
        })
        .catch((err) => {
          this.$message.error(JSON.stringify(err))
        })
    },

    //查询产品编码
    getMaterial1(query) {
      return new Promise(resovle => {
        let params = {
          customerId: this.demand.customValue,
          ps: 20,
          pn: 1
        }
        if (query) {
          params['code_like'] = query
        }

        this.demand.productCodeValue =  '' //产品编码值
        this.demand.productName = '' //产品名称
        this.demand.proSpecification = '' //产品规格
        // let params = ''
        this.$quote.getComboMaterial1(params).then((res) => {
          console.log(res)
          if (res.code == 200) {
            this.productCode = res.data.rows
            resovle()
          } else {
            this.$message.error(res.code + '-' + res.msg)
          }
        })
      })
      
    },

    //查询合作主体
    getOrganization() {
      this.$params
        .getOrganization()
        .then((res) => {
          console.log(res)
          if (res.code == 200) {
            this.isCompany = res.data
            console.log(this.isCompany)
          } else {
            this.$message.error(res.code + '-' + res.msg)
          }
        })
        .catch((err) => {
          this.$message.error(JSON.stringify(err))
        })
    },

    //查询客制治具
    getFixt1() {
      this.$quote
        .getFixture1()
        .then((res) => {
          console.log(res)
          if (res.code == 200) {
            this.forFixtures = res.data.rows
          } else {
            this.$message.error(res.code + '-' + res.msg)
          }
        })
        .catch((err) => {
          this.$message.error(JSON.stringify(err))
        })
    },

    //查询合作模式
    getComboCoop() {
      this.$quote
        .getComboCoopMode()
        .then((res) => {
          console.log(res)
          if (res.code == 200) {
            this.cooperation = res.data
          } else {
            this.$message.error(res.code + '-' + res.msg)
          }
        })
        .catch((err) => {
          this.$message.error(JSON.stringify(err))
        })
    },
    /* 上传文件 */
    uploadFile(files) {
      console.log(files)
      files.map((item) => {
        this.demand.upFile.push(item.id)
      })
    },
    btnAdd() {
      // this.pageLoading = true
      this.$refs.demand.validate((valid) => {
        if (valid) {
          let param = {
            customer: this.demand.customValue,
            coopFactory: this.demand.factoryValue,
            productCode: this.demand.productCodeValue,
            productName: this.demand.productName,
            productType: this.demand.typeValue,
            productSpec: this.demand.proSpecification,
            process: [], //加工工艺
            wastageRate: {
              //耗损率
              A: this.demand.coefficientA,
              B: this.demand.coefficientB,
              C: this.demand.coefficientC,
            },
            customerFile: this.demand.upFile, //客户文件
            coopMode: this.demand.cooperationValue, //合作模式"
            includeTax: this.demand.isRevenueValue, //是否含税
            coopCompany: this.demand.companyValue, //我司合作主体
            shippingRequirement: this.demand.requirementValue, //出货要求
            materialRepurchase: this.demand.buyBackValue, //库存物料是否回购
            materialRepurchaseDays: this.demand.buyBackData, //库存物料回购天数
            accountingCycle: this.demand.period, //对账周期 (天)
            accountingPeriod: this.demand.paymentDay, //账期 (天)
            remark: this.demand.textarea, //备注说明
            advanceRate: this.demand.advanceProp, //垫资比例
            logisticsChargeType: this.demand.logisticsChargeType, //物流费方式

            // rebate: this.demand.factoryValue, //返利
            // scrapRate: '1.2', //报废率
            // fixtureFrom: '1', //客供治具
            // materialFile: '', //物料清单文件",
            // bomFile: '', //'bom清单文件',
            // purchaseMaterialFile: '', //"代采物料文件",
            // purchaseMaterialPriceFile: '', //"代采物料询价文件",
          }
          this.demand.processingVaule.forEach(item => {
            param.process.push(this.processingMap[item])
          })
          // let param = {
          //   customer: '304774',
          //   factory: '富润通',
          //   productCode: '501-DZ0000464',
          //   productName: '1',
          //   accountingCycle: '',
          //   accountingPeriod: '1',
          //   coopCompany: '品鑫泰供应链（深圳）有限公司',
          //   coopMode: 'DC_JG',
          //   customer: '304774',
          //   customerFile: ['1484095943742218241'],
          //   factory: '富润通',
          //   includeTax: '1',
          //   materialRepurchase: '',
          //   materialRepurchaseDays: '11',
          //   process: ['TEST', 'SMT'],
          //   productCode: '501-DZ0000464',
          //   productName: '1',
          //   productSpec: '钉钉人脸考勤机M1Y',
          //   productType: '内存条',
          //   remark: '11',
          //   shippingRequirement: '1',
          //   wastageRate: { A: '1', B: '1', C: '1' },
          // }

          this.$params
            .pCostQuote(param)
            .then((res) => {
              console.log(res)
              if (res.code == 200) {
                this.$message({
                  message: '添加成功！',
                  type: 'success',
                })
                this.$router.go('-1')
              } else {
                this.$message.error(res.code + '-' + res.msg)
              }
              this.pageLoading = false
            })
            .catch((err) => {
              this.$message.error(JSON.stringify(err))
            })
        } else {
          return false
        }
      })
    },

    btnBack() {
      this.$router.go(-1)
    },

    /* 客户名称选择 */
    selectCust(value) {
      this.demand.customValue = value
      this.getMaterial1()
      console.log(this.demand.customValue)
    },
    selectFatory(value) {
      this.demand.factoryValue = value
      console.log(this.demand.factoryValue)
    },
    selectType(value) {
      this.demand.typeValue = value
      console.log(this.demand.typeValue)
    },
    selectCode(value) {

      this.demand.productCodeValue = value.code
      this.demand.proSpecification = value.spec
      this.demand.productName = value.name

    },
    seleFixtures(value) {
      this.demand.fixtures = value
      console.log(this.demand.fixtures)
    },

    seleRevenue(value) {
      this.demand.isRevenueValue = value
      console.log(this.demand.isRevenueValue)
    },

    seleCompany(value) {
      this.demand.companyValue = value
      console.log(this.demand.companyValue)
    },

    onChange1(value) {
      this.demand.cooperationValue = value
      if (this.demand.cooperationValue == 'DZ_JG') {
        this.isShow = true
      } else {
        this.isShow = false
      }
      console.log(value)
    },
    onChange2(value) {
      this.demand.requirementValue = value
      console.log(value)
    },
    onChange3(value) {
      this.demand.buyBackValue = value
      if (this.demand.buyBackValue == '1') {
        this.hgShow = true
      } else {
        this.hgShow = false
      }
      console.log(value)
    },

    onChange4(value) {
      this.demand.logisticsChargeType = value
      console.log(this.demand.logisticsChargeType)
    },

    handleCheckedCitiesChange(value) {
      this.demand.processingVaule = value
      console.log(this.demand.processingVaule)
    },
    btnShow() {
      if (this.show == true) {
        this.show = false
        this.isShows = true
        this.demand.productCodeValue = ''
        this.demand.proSpecification = ''
        this.newCode = '返回选择'
      } else {
        this.show = true
        this.isShows = false
        this.newCode = '添加新编码'
      }
    },
  },
}
</script>

<style scoped lang="less">
.mainDiv {
  background-color: #f3f5fa;
  width: 100%;
  float: left;
  height: auto;
  .topDiv {
    width: 98%;
    margin: 20px 1%;
    height: 50px;
    line-height: 50px;
    background-color: #fff;
    .justBackColor {
      height: 30px;
      width: 5px;
      margin: 10px;
      float: left;
      background-color: #3377ff;
    }
    p {
      width: 200px;
      height: 50px;
      line-height: 50px;
      font-size: 15px;
    }
  }
  .justDiv {
    width: 98%;
    margin: 15px 1%;
    height: 850px;
    padding-top: 30px;
    background-color: #fff;
    .justDivCon {
      width: 92%;
      margin: 5px 4%;
      float: left;
      em {
        color: red;
        margin: 0 10px;
      }
      span {
        display: inline-block;
        margin-left: 0px;
      }
      .flex{
        display: flex;
      }
    }
    .btnBtom {
      width: 100%;
      margin: 50px 0 10px 0;
      float: left;
      text-align: center;
    }
  }
}
</style>